const app = getApp()
import * as echarts from '../../ec-canvas/echarts';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    type:1, //1班级健康报告数据  2 班级学生列表

     //班级选择----------begin
     bottom:false,
     //校区
     schoolArealist:[],
     schoolArea:'',
     schoolAreaKey:'',
     //班级类型
     classTypes: [],
     classTypesKey:'',
     //学段
     // seasons:[],
     // seasonKey:'',
     // seasonName:'',
     //年级
     grades:[],
     gradeKey:"",
     gradeName:'',
     //班级
     classs:[],
     classKey:'',
     className:'',
     viewName:'更换班级',
     isShowDetail:true,


     middleShow:false,
     studentId:'',

     //国家体测数据
     cycleId:'',
     testCycleData:[],

     valName:'',

     ifLoad:true,

     //班级健康报告
     viewData:{},

    //学生列表
     stuList:[],

     yxl:0, //优秀率
     lhl:0, //良好率
     jgl:0, //及格率
     bjgl:0, //不及格率

     //柱状图数据
     barTitle:[],
     barDatas:[],
     ifShowBar:false,

     excellent:[],
     good:[],
     pass:[],
     fail:[],

    // 
    
    //饼图数据
    pieEc:{
      lazyLoad: true,
    },

    //柱图
    barEc:{
      lazyLoad: true,
    },
    seriesBarVal:[]
  },


 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {  
    this.getTeachCycle()
    this.getSchoolArea()
    
  },

 //饼图
 drawPie:function(){

  let ecComponentdrawPie = this.selectComponent('#mychart-dom-pie');

  ecComponentdrawPie.init((canvas, width, height, dpr) => {
    // 获取组件的 canvas、width、height 后的回调函数
    // 在这里初始化图表
 
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
  
    canvas.setChart(chart);

    var option = {
      colors:['#3acc8c', '#5874fc', '#feb82f', '#f9605e'],
      
      // tooltip: {
      //   trigger: 'item'
      // },
      // legend: {
      //   selectedMode:false,//取消图例上的点击事件
      //   top: '5%',
      //   left: 'center'
      // },
      series: [
        {
          //name: 'Access From',
          type: 'pie',
          
          radius: ['50%', '80%'],
          avoidLabelOverlap: false,
          label: {
            show: false,
            position: 'center'
          },
          // emphasis: {
          //   label: {
          //     show: true,
          //     fontSize: '11',
          //     //fontWeight: 'bold'
          //   }
          // },
          labelLine: {
            show: false
          },
          data: [
            { value: this.data.yxl,name:"优秀率:"+ this.data.yxl},
            { value: this.data.lhl,name:"良好率:"+ this.data.lhl},
             { value: this.data.jgl,name:"及格率:"+this.data.jgl},
             { value: this.data.bjgl,name:"不及格率:"+this.data.bjgl}
          ]
        }
      ]
    };
    chart.setOption(option);
    //chart.off("click"); //取消echarts 点击事件
    return chart;
  });
},


//柱图
drawBar:function(){
  // if(ecComponentdrawBar == null){
  //   ecComponentdrawBar = this.selectComponent('#mychart-dom-bar');
  // }
  let ecComponentdrawBar = this.selectComponent('#mychart-dom-bar');
  ecComponentdrawBar.init((canvas, width, height, dpr) => {
    // 获取组件的 canvas、width、height 后的回调函数
    // 在这里初始化图表
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
  
    canvas.setChart(chart);

    var option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {},
      grid: {
        left: '3%',
        right: '3%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: [
        {
          type: 'category',
          data: this.data.barTitle,//['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          axisLabel: {
             fontSize:12,
             color: '#000',
             interval: 0,
             rotate:'35',// 旋转度数
           },
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: [
        {
          name: '优秀',
          type: 'bar',
          barWidth: 15,
          stack: 'Search Engine',
          emphasis: {
            focus: 'series'
          },
          data:this.data.excellent
        },
        {
          name: '良好',
          barWidth: 15,
          type: 'bar',
          stack: 'Search Engine',
          emphasis: {
            focus: 'series'
          },
          data: this.data.good
        },
        {
          name: '及格',
          type: 'bar',
          barWidth: 15,
          stack: 'Search Engine',
          emphasis: {
            focus: 'series'
          },
          data: this.data.pass
        },
        {
          name: '不及格',
          type: 'bar',
          barWidth: 15,
          stack: 'Search Engine',
          emphasis: {
            focus: 'series'
          },
          data: this.data.fail//[62, 82, 91, 84, 109, 110, 120]
        }
      ]
    };
    chart.setOption(option);
    //chart.off("click"); //取消echarts 点击事件
    return chart;
  });
},

  onClickBanji(){
    this.setData({
      type:1
    })
    this.drawPie()
    if(this.data.ifShowBar){
      this.drawBar()
    }

    // chart.setOption(this.setPieoption());
    // if(this.data.ifShowBar){
    //   barChart.setOption(this.setDrawoption());
    // }
  },
  onClickGeren(){
    this.setData({
      type:2
    })
  },

    //提测弹框消失回调
  hiddenAlert(){
    console.log("弹框异常了");
    this.setData({
      middleShow:false,
      bottom:false
    })
    if(this.data.type == 1){
      this.drawPie()
      if(this.data.ifShowBar){
        this.drawBar()
      }
    }
    
   
    // chart.setOption(this.setPieoption());
    // if(this.data.ifShowBar){
    //   barChart.setOption(this.setDrawoption());
    // }
  },

  
  didClickActionShow1(){
    var action =  this.selectComponent("#action-sheet1");
    action.onShowSingelAlert(this.data.schoolArealist,1);
   },

   didClickActionShow2(){
    var action =  this.selectComponent("#action-sheet2");
    action.onShowSingelAlert(this.data.grades,1);
   },

   didClickActionShow3(){
    var action =  this.selectComponent("#action-sheet3");
    action.onShowSingelAlert(this.data.classs,1);
   },

  didClickUp(){
    this.setData({
      isShowDetail:false
    })
  },
  actionSheetIndex1(e){
    console.log(this.data.schoolArea+'==选择的数据='+e.detail.name)
    if(this.data.schoolArea != e.detail.name){
      this.setData({
        schoolArea:e.detail.name,
        schoolAreaKey:e.detail.key
      })
      this.getClassType(1)
    }
  },
  radioChange(res){
    console.log('选择班级的数据='+JSON.stringify(res))
    //console.log("33333=="+res.detail.value);
    this.setData({
      classTypesKey:res.detail.value
    })
    this.getClassType(3)
  },
  actionSheetIndex2(e){
   // console.log('选择的数据='+e.detail.key)
    //console.log('选择的数据='+e.detail.name)
    this.setData({
      gradeName:e.detail.name,
      gradeKey:e.detail.key
    })
    this.getClassType(4)
  },
  actionSheetIndex3(e){
    //console.log('选择的数据='+e.detail.key)
    //console.log('选择的数据='+e.detail.name)
    this.setData({
      className:e.detail.name.indexOf('班')!=-1?e.detail.name:e.detail.name+"班",
      classKey:e.detail.key
    })
  },

  //获取校区
  getSchoolArea(){
    app.api.getSchoolArea().then(rest => {
      if(rest&&rest.success){   
        if(rest.data.list!=null && rest.data.list.length > 0){
           this.setData({
            schoolArealist:rest.data.list,
            schoolArea:rest.data.list[0].name,
            schoolAreaKey:rest.data.list[0].key
           })
           this.getClassType(1)
        }
        console.log('接口校区数据='+JSON.stringify(rest))
      }else{
        //console.log('接口校区数据=='+rest.errMsg)
        wx.showToast({
          title: rest.errMsg||'网络异常，请稍后重试！！',
          icon: 'none',
          duration: 2000,
          mask:true
        })
      }
    })
    .catch(r => {
      console.error(r)
      wx.showToast({
        title: '网络异常，请稍后重试！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    })
  
  },


  //获取班级类型
  getClassType(resultType){
    var that = this
    var datas
    if(resultType == 1){
      datas = {
        schoolId:this.data.schoolAreaKey,
        resultType:resultType,
        pageNo:1,
        pageSize:50,
      }
    }else if(resultType == 2){
      datas = {
        schoolId:this.data.schoolAreaKey,
        resultType:resultType,
        pageNo:1,
        pageSize:50,
        type:this.data.classTypesKey,
      }
    }else if(resultType == 3){
      datas = {
        schoolId:this.data.schoolAreaKey,
        resultType:resultType,
        pageNo:1,
        pageSize:50,
        type:this.data.classTypesKey,
        //section:this.data.seasonKey,
      }
    }else if(resultType == 4){
      datas = {
        schoolId:this.data.schoolAreaKey,
        resultType:resultType,
        pageNo:1,
        pageSize:50,
        type:this.data.classTypesKey,
        //section:this.data.seasonKey,
        grade:this.data.gradeKey,
      }
    }
    console.log('接口班级类型参数='+JSON.stringify(datas))
    app.api.getClassInfos(datas).then(rest => {
      if(rest&&rest.success){   
        if(rest.data.list!=null && rest.data.list.length > 0){    
          
          if(resultType == 1){
            this.setData({
              classTypes:rest.data.list,
             })
             this.data.classTypes[0].checked = 'true'
             this.setData({
              classTypes:rest.data.list,
              classTypesKey:rest.data.list[0].key
             })
             that.getClassType(3)
          }
          // else if(resultType == 2){
          //    this.setData({
          //     seasons:rest.data.list,
          //     seasonKey:rest.data.list[0].key,
          //     seasonName:rest.data.list[0].name,
          //    })
          //    that.getClassType(3)
          // }
          else if(resultType == 3){
            this.setData({
              grades:rest.data.list,
              gradeKey:rest.data.list[0].key,
              gradeName:rest.data.list[0].name,
            })
            that.getClassType(4)
          }else if(resultType == 4){
            this.setData({
              classs:rest.data.list,
              classKey:rest.data.list[0].key,
              className:rest.data.list[0].name.indexOf('班')!=-1?rest.data.list[0].name:rest.data.list[0].name+"班",
            })
           // console.log("kkkkkkkkkkkkkk"+this.data.gradeName+this.data.className);
            if(this.data.ifLoad){
              this.setData({
                valName:this.data.gradeName+this.data.className,
                ifLoad:false
              })
            }
            if(this.data.cycleId!=null && this.data.cycleId!=''){
              this.getPhysicalReportClass()
            }else{
              //获取国家体测
              this.getTeachCycle()
            }
            
          }
        }else{
          //没有数据复位
          if(resultType == 1){
             this.setData({
              classTypes:[],
              classTypesKey:'',
              // seasons:[],
              // seasonKey:'',
              // seasonName:'',
              grades:[],
              gradeKey:'',
              gradeName:'',
              classs:[],
              classKey:'',
              className:'',
             })
          }else if(resultType == 2){
             this.setData({
              // seasons:[],
              // seasonKey:'',
              // seasonName:'',
              grades:[],
              gradeKey:'',
              gradeName:'',
              classs:[],
              classKey:'',
              className:'',
             })
            
          }else if(resultType == 3){
            this.setData({
              grades:[],
              gradeKey:'',
              gradeName:'',
              classs:[],
              classKey:'',
              className:'',
            })
           
          }else if(resultType == 4){
            this.setData({
              classs:[],
              classKey:'',
              className:'',
            })
          }
        }
        console.log('接口数据='+JSON.stringify(rest))
      }else{
       // console.log('接口数据=='+rest.errMsg)
        wx.showToast({
          title: rest.errMsg||'网络异常，请稍后重试！！',
          icon: 'none',
          duration: 2000,
          mask:true
        })
      }
    })
    .catch(r => {
      console.error(r)
      wx.showToast({
        title: '网络异常，请稍后重试！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    })
  },


  bottomPop() {
  	this.setData({
  		bottom: true
    })
    //this.getSchoolArea()

  },
  cancelPopup(){
    this.hidePop()
  },

  //班级选择弹框
  okPopup(){
    this.hidePop()

    if(this.data.className!=''){
      this.setData({
        valName:this.data.gradeName+this.data.className,
        pageNo:1,
        dataList:[],
        totalPage:0,
        viewName:this.data.className
      })
      // if(this.data.type == 2){
      //   this.getStuList()
      // }else{
      //   this.getPhysicalReportClass()
      // }
      this.getPhysicalReportClass()
      this.getStuList()
     
    }
  },


  allClass(){
    this.hidePop()
    this.setData({
      pageNo:1,
      dataList:[],
      totalPage:0,
      viewName:'全部班级',
      classKey:''
    })
    this.getStuList()
  },

  hidePop () {
    this.setData({
      bottom:false,
    })
    if(this.data.type == 1){
      this.drawPie()
      if(this.data.ifShowBar){
        this.drawBar()
      }
    }
   
    // 关闭select  .对应class #对应id
    this.selectComponent('#popup').hidePop()
  },


  getStuList(){
    wx.showLoading({
      title: '数据加载中...',
      icon: 'none',
    })
    var data = {
          pageNo:this.data.pageNo,
          pageSize:this.data.pageSize,
          classId:this.data.classKey,
          status:"1"
        }
    //console.log('接口学生列表参数='+JSON.stringify(data))
    app.api.getStuList(data).then(rest => {
      wx.hideLoading()
      if(rest&&rest.success){   
        if(rest.data.studentList!=null && rest.data.studentList.length > 0){
          this.setData({
            stuList:rest.data.studentList
          })
        }
        console.log('接口学生列表数据='+JSON.stringify(rest))
      }else{
        console.log('接口数据=='+rest.errMsg)
        wx.showToast({
          title: rest.errMsg||'网络异常，请稍后重试！！',
          icon: 'none',
          duration: 2000,
          mask:true
        })
      }
    })
    .catch(r => {
      console.error(r)
      wx.showToast({
        title: '网络异常，请稍后重试！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    })
  },

  onClickStu(ret){
    console.log('接口参数sssss='+JSON.stringify(ret.currentTarget))

    wx.navigateTo({
      url: '/pages/record/physicalHealthReport?studentId='+ret.currentTarget.dataset.studentid,  //家长处方详情
    })
  },


  // 体测选择-------------------------------------
  //弹框选择体测回调方法
  getCycleId(ret){
    this.setData({
      cycleId:ret.detail.val,
      middleShow:false
    })

    this.getPhysicalReportClass()
  },

  //周期切换
  showCycleAlert(){
      this.setData({
        middleShow:true
      })
  },
//获取教学周期
getTeachCycle(){
  var that = this
  wx.showLoading({
    title: '数据加载中...',
    icon: 'none',
  })

  app.api.getTeachCycle().then(rest => {
    wx.hideLoading()
    if(rest&&rest.success){   
      console.log('接口数据b='+JSON.stringify(rest.data))

      if(rest.data.list!=null && rest.data.list.length>0){
         that.getTestCycle(rest.data.list[0].key)
      }
    }else{
      //console.log('接口数据=='+rest.errMsg)
      wx.showToast({
        title: rest.errMsg||'网络异常，请稍后重试！！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    }
  })
  .catch(r => {
    wx.hideLoading()
    console.error(r)
    wx.showToast({
      title: '网络异常，请稍后重试！',
      icon: 'none',
      duration: 2000,
      mask:true
    })
  })
},


//获取体测周期
getTestCycle(iTeachCycleId){
  var that = this
  wx.showLoading({
    title: '数据加载中...',
    icon: 'none',
  })
  var datas = {
    teachCycleId:iTeachCycleId,
    type:"2"
  }
  //console.log('接口参数='+JSON.stringify(datas))
  app.api.getTestCycle(datas).then(rest => {
    wx.hideLoading()
    if(rest&&rest.success){   
      console.log('接口数据c='+JSON.stringify(rest.data))

      if(rest.data.list!=null && rest.data.list.length>0){
        that.setData({
           testCycleData:rest.data.list,
           cycleId:rest.data.list[0].key
         })

         if(this.data.classKey!=null && this.data.classKey!=''){
          this.getPhysicalReportClass()
         }
         
      }
    }else{
      console.log('接口数据=='+rest.errMsg)
      wx.showToast({
        title: rest.errMsg||'网络异常，请稍后重试！！',
        icon: 'none',
        duration: 2000,
        mask:true
      })
    }
  })
  .catch(r => {
    wx.hideLoading()
    console.error(r)
    wx.showToast({
      title: '网络异常，请稍后重试！',
      icon: 'none',
      duration: 2000,
      mask:true
    })
  })
},




//老师-班级体质健康报告
getPhysicalReportClass(){
  var that = this
  wx.showLoading({
    title: '数据加载中...',
    icon: 'none',
  })
  var datas = {
    cycleId:this.data.cycleId,
    classId:this.data.classKey
  }
  //console.log('接口老师-班级体质健康报告参数='+JSON.stringify(datas))
  app.api.getPhysicalReportClass(datas).then(rest => {
    wx.hideLoading()
    if(rest&&rest.success){   
      console.log('接口老师-班级体质健康报告数据c='+JSON.stringify(rest.data))
      this.setData({
        viewData:rest.data
      })
      this.setLv(rest.data)
    }else{
      //console.log('接口老师-班级体质健康报告数据=='+rest.errMsg)
      wx.showToast({
        title: '网络异常，请稍后重试！！',
        icon: 'none',
        duration: 800,
        mask:true,
        complete: function (res) {
          setTimeout(function(){
            wx.navigateBack({
              delta: 1,  // 返回上一级页面。
              success: function() {           
              }
            })
          },800)
        }
      })
    }
  })
  .catch(r => {
    wx.hideLoading()
    console.error(r)
    wx.showToast({
      title: '网络异常，请稍后重试！',
      icon: 'none',
      duration: 2000,
      mask:true
    })
  })
},

//设置图标值
setLv(data){
  console.log('率计算元数据='+JSON.stringify(data))
  var totale = 0
  if(data!=null){
    totale = data.excellent+data.good+data.pass+data.unpass
    if(totale >0){
      this.setData({
        yxl:(data.excellent/totale).toFixed(2), //优秀率
        lhl:(data.good/totale).toFixed(2), //良好率
        jgl:(data.pass/totale).toFixed(2), //及格率
        bjgl:(data.unpass/totale).toFixed(2), //不及格率
      })
    }
    //柱状图数据
    if(data.itemScore!=null && data.itemScore.length>0){
      var vBarTitle = []

      var vexcellent = []
      var vgood = []
      var vpass = []
      var vfail = []
  
     
      for(var i=0;i<data.itemScore.length;i++){
        if(data.itemScore[i].itemName!='身高' && data.itemScore[i].itemName!='体重'){
          vBarTitle.push(data.itemScore[i].itemName)
          vexcellent.push(data.itemScore[i].excellent)
          vgood.push(data.itemScore[i].good)
          vpass.push(data.itemScore[i].pass)
          vfail.push(data.itemScore[i].fail)
        }  
      }
    
    
      this.setData({
        ifShowBar:true,
        barTitle:vBarTitle,
        
        excellent:vexcellent,
        good:vgood,
        pass:vpass,
        fail:vfail,
      })
    }else{
      this.setData({
        ifShowBar:false
      })
      
    }

  }
  console.log("============"+this.data.barTitle);
  console.log("============"+this.data.excellent);
  console.log("============"+this.data.good);
  console.log("============"+this.data.ifShowBar);
  if(!this.data.bottom && !this.data.middleShow){
    if(this.data.type == 1){
      this.drawPie()
      if(this.data.ifShowBar){
        this.drawBar()
      }
    }
  }  
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})